// pages/Classv/Classv.js
const Aotu = require('../../utils/auth')
const {
  GoShop,
  ShopPrice
} = require('../../utils/api')
const {
  Fen,
  Erecom,
  Detail,
  PeiShop
} = require('../../utils/api')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ClassArr: [],
    Right: [],
    value: '',
    Index: 339312,
    Flag: false,
    show: false,
    Ids: 0,
    Ids1: 0,
    properties: [],
    pei: [],
    pei1: [],
    PeijianId: [],
    flags: false,
    flags1: false,
    GoodsId: 0,
    Cun: 0,
    SukId: 0,
    Num: 1,
    MinPrice: 0,
    OPrice: 0,
    Number: 1,
  },
  getlist() {
    Fen().then((res) => {
      console.log(res);
      this.setData({
        ClassArr: res
      })
    })

  },
  // 加入购物车
  Goshop(e) {
    console.log(e.target.dataset.obj);
    GoShop({
      goodsId: e.target.dataset.obj.id,
      number: e.target.dataset.obj.minBuyNumber,
      token: wx.getStorageSync('token')
    }).then((res) => {
      console.log(res);
      wx.showToast({
        title: '成功加入购物车',
      })
    })
  },
  // 加入购物车有规格的
  Shops() {
    this.Prices()
    // 配件的信息
    const skuGoods = this.data.pei1
    console.log(skuGoods);
    // 商品详情信息
    const porper = this.data.properties
    // 存放sku的数组
    const sku = []
    if (porper.properties) {
      console.log(porper.properties);
      porper.properties.forEach(item => {
        const is = item.childsCurGoods.find(item1 => {
          return item1.active
        })
        // 如果active是false就return出去
        if (!is) {
          return
        }
        sku.push({
          optionId: is.propertyId,
          optionValueId: is.id
        })
        console.log(sku);
      })
    }
    // 父id子id
    const goodstion = []
    if (this.data.pei1) {
      this.data.pei1.forEach(item => {
        item.items.forEach(item1 => {
          if (item1.active) {
            goodstion.push({
              id: item1.id,
              pid: item1.pid
            })
            console.log(goodstion);
          }
        })
      })
    }
    GoShop({
      goodsId: porper.basicInfo.id,
      number: this.data.Number,
      sku: JSON.stringify(sku),
      addition: JSON.stringify(goodstion),
      token: wx.getStorageSync('token')
    }).then((res) => {
      console.log(res);
    })
    wx.showToast({
      title: '成功加入购物车',
    })
    this.onClose()

  },
  // 选取规格样式
  GuiGe1(e) {
    let content = this.data.properties
    // console.log(this.data.properties);
    // console.log(this.data.Right);
    // 父下标
    let selectIndex = e.currentTarget.dataset.selectIndex * 1;
    // 子下标
    let attrIndex = e.currentTarget.dataset.attrIndex;
    // 父数据
    // console.log(content);
    // 点击到的父元素
    const proper = content.properties[selectIndex]
    // 点击到的子元素
    const child = proper.childsCurGoods[attrIndex]
    // 给每一个规格一个状态
    for (let index = selectIndex; index < content.properties.length; index++) {
      const element = content.properties[index]
      element.optionValueId = null
      element.childsCurGoods.forEach(item => {
        item.active = false
      })

    }
    // 处理选中的规格
    proper.childsCurGoods.forEach(item1 => {
      if (item1.id == child.id) {
        item1.active = true
      } else {
        item1.active = false
      }
    })
    // 没有的sku 不然选中
    let _skulist = content.skuList
    content.properties.forEach(item => {
      item.childsCurGoods.forEach(item1 => {
        if (item1.active) {
          _skulist = _skulist.filter(item3 => {
            return item3.propertyChildIds.indexOf(item.id + ':' + item1.id) != -1
          })
        } else if (!item.optionValueId) {
          const next = _skulist.find(item4 => {
            return item4.propertyChildIds.indexOf(item.id + ':' + item1.id) != -1
          })
          item1.hidden = (next || item.id == proper.id) ? false : true
        }
      })
    })
    this.setData({
      properties: content
    })
    // console.log(this.data.pei);
    this.Prices()

  },
  // 商品配件
  GuiGe2(e) {
    let that = this
    // 父下标
    let selectIndex = e.currentTarget.dataset.selectIndex * 1;
    // 子下标
    let attrIndex = e.currentTarget.dataset.attrIndex;
    let content = e.currentTarget.dataset.content
    // var count = content.items.length
    console.log(content);
    console.log(selectIndex);
    // console.log(this.data.pei);
    // console.log(this.data.pei1);
    // 第一层名字
    const proper = content[selectIndex]
    console.log(proper);
    console.log('子下表', attrIndex);
    // 配件名
    const child = proper.items[attrIndex]
    console.log(child);
    if (child.active) {
      child.active = false
      this.setData({
        pei1: content
      })
      this.Prices()
      return
    }
    if (proper.type == 0) {
      proper.items.forEach(item => {
        item.active = false
      })
    }
    child.active = true
    this.setData({
      pei1: content
    })
    this.Prices()

  },
  // 搜索
  search(e) {
    console.log(e.detail);
    wx.redirectTo({
      url: `/pages/Shoplist/Shoplist?obj=${this.data.value}`,
    })
  },
  // 切换
  Cut(e) {
    this.setData({
      Index: e.target.id
    })
    // console.log(e.target.id);

    Erecom({
      categoryId: this.data.Index
    }).then((res) => {
      console.log(res);
      var vc = false
      if (!res.code) {
        vc = false
      } else {
        vc = true
      }
      this.setData({
        Right: res.result,
        Flag: vc
      })
    })
  },
  // 计数器加
  Jia() {
    let porperNum = this.data.Number
    porperNum++
    console.log(porperNum);
    this.setData({
      Number: porperNum
    })
  },
  // 计算价格
  Prices() {
    // 计算最终的商品价格
    let price = this.data.properties.basicInfo.minPrice
    //计算原始价格
    let originalPrice = this.data.properties.basicInfo.originalPrice
    //最低积分
    let totalScoreToPay = this.data.properties.basicInfo.minScore
    //获取库存数量
    let buyNumMax = this.data.properties.basicInfo.stores
    //获取最低购买数量
    let buyNumber = this.data.properties.basicInfo.minBuyNumber
    // 计算 sku 价格
    const needNum = this.data.properties.properties ? this.data.properties.properties.length : 0
    //统计用户选中了几个规格
    let SelectNum = 0;
    let ChildIds = "";
    let ChildNames = "";
    //判断当前商品有没有properties属性，有代表sku
    if (this.data.properties.properties) {

      //第一层循环 
      this.data.properties.properties.forEach(item => {

        // 第二层循环
        item.childsCurGoods.forEach(item1 => {
          //如果当前选中的规格为true
          if (item1.active) {
            //规格的数量
            SelectNum++;
            //拼接propertyChildIds规格字符串
            ChildIds = ChildIds + item.id + ":" + item1.id + ",";
            ChildNames = ChildNames + item.name + ":" + item1.name + "  ";
          }
        })
      })
    }
    let Submit = true;
    if (needNum != SelectNum) {
      Submit = false;
    }
    // 计算可选配件
    if (this.data.properties.basicInfo.hasAddition && this.data.pei1) {
      this.data.pei1.forEach(item => {
        if (item.required) {
          const ac = item.items.find(item1 => {
            return item1.active
          })
          if (!ac) {
            Submit = false
          }
        }
      })
    }
    if (Submit) {
      let token = wx.getStorageSync('token')
      ShopPrice({
        token: token ? token : '',
        goodsId: this.data.properties.basicInfo.id,
        propertyChildIds: ChildIds
      }).then((res) => {
        price = res.price
        originalPrice = res.originalPrice
        totalScoreToPay = res.score
        buyNumMax = res.stores
        this.setData({
          Submit,
          MinPrice: res.price,
          OPrice: res.originalPrice,
          totalScoreToPay: res.score,
          buyNumMax: res.stores,
          buyNumber: (buyNumMax >= buyNumber) ? buyNumber : 0
        });
      })

    }
  },
  // 唤起弹框
  Adds(e) {
    wx.hideTabBar()
    let obj = e.currentTarget.dataset.obj
    // 如果这个属性为true
    if (obj.hasAddition) {
      PeiShop({
        goodsId: e.target.id,
        token: wx.getStorageSync('token')
      }).then((res) => {
        console.log(res);
        this.setData({
          pei: res[0],
          pei1: res
        })
        console.log(this.data.pei);
        console.log(this.data.pei1);
      })
    }
    // 商品详情
    Detail({
      id: e.target.id
    }).then((res) => {
      console.log(res);
      const goods = res
      this.setData({
        show: true,
        properties: res,
        GoodsId: e.target.id,
        MinPrice: goods.basicInfo.minPrice,
        Number: goods.basicInfo.minBuyNumber,
        //商品原始价格
        OPrice: goods.basicInfo.originalPrice,
      })
      // 原始价格
      console.log(this.data.OPrice, goods.basicInfo.originalPrice);
      // 最低价格
      console.log(this.data.MinPrice, goods.basicInfo.minPrice);
    })


    console.log(e.target.dataset.obj);
  },
  // 关闭弹框
  onClose() {
    wx.showTabBar()
    this.setData({
      show: false,
      Number: 1,
    })
    // this.data.Num = 1
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //   点击主页分类跳转数据
  onLoad(options) {
    console.log(options.id);
    // console.log(this.data.Index);
    let Index = options.id
    Erecom({
      categoryId: Index || this.data.Index
    }).then((res) => {
      console.log(res);
      var vc = false
      if (!res.code) {
        vc = false
      } else {
        vc = true
      }
      this.setData({
        Right: res.result,
        Flag: vc,
        Index: Index,
      })
    })
    this.getlist()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('OnShow');

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log('pull down.');
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})